package com.android.driveuploader;

/**
 * Created by srikanthg on 8/27/14.
 */
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

import android.accounts.AccountManager;
import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Activity for creating a meme.
 */
public class CreateMemeActivity extends ActionBarActivity {

    private static final class CopyTextWatcher implements TextWatcher {
        private final TextView textView;

        public CopyTextWatcher(TextView destination) {
            textView = destination;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            textView.setText(s.toString());
        }
    }

    /**
     * Fragment that displays the meme.
     */
    public static class MemeFragment extends Fragment {
        @Override
        public View onCreateView(
                LayoutInflater inflater,
                ViewGroup container,
                Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_meme, container, false);
        }
    }

    /**
     * Fragment that displays the input text fields for the memes.
     */
    public static class InputMemeTextFragment extends Fragment {
        @Override
        public View onCreateView(
                LayoutInflater inflater,
                ViewGroup container,
                Bundle savedInstanceState) {
            // Inflate the layout for this fragment.
            return inflater.inflate(
                    R.layout.fragment_input_meme_text,
                    container,
                    false);
        }
    }

    class DownloadImageAsyncTask extends AsyncTask<Uri, Void, Bitmap> {
        private Uri uri;
        @Override
        protected Bitmap doInBackground(Uri... params) {
            uri = params[0];
            try {
                return BitmapFactory.decodeStream(getInputStream(uri));
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error reading bitmap", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                memeTemplate.setImageBitmap(result);
                // Use file name as content description.
                memeTemplate.setContentDescription(uri.getLastPathSegment());
            }
        }

        private InputStream getInputStream(Uri uri) throws IOException {
            if (uri.getScheme().startsWith("http")) {
                return (InputStream) new URL(uri.toString()).getContent();
            } else {
                return getContentResolver().openInputStream(uri);
            }
        }
    }

    private static final String LOG_TAG = CreateMemeActivity.class.getCanonicalName();
    private static final String IMAGE_URL = "https://lh3.googleusercontent.com/-N9D2G4_WVG4/"
            + "UFHvJh4_mFI/AAAAAAAAfgI/lRmmiQgAtOg/s1440/P8050125.JPG";
    private static final String IMAGE_URL_EXTRA = "meme_url";

    private static final int IMAGE_CAPTURE_REQUEST_CODE = 1;
    private static final int PICK_ACCOUNT_REQUEST_CODE = 2;
    private static final int AUTHENTICATION_RETRY_REQUEST_CODE = 3;

    public static String token;

    private ImageView memeTemplate;
    private ViewGroup meme;
    private Uri photoUri;
    private String accountName = null;

    public static Intent createIntent(Context context, String imageUrl) {
        Intent intent = new Intent(context, CreateMemeActivity.class);
        intent.putExtra(IMAGE_URL_EXTRA, imageUrl);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(LOG_TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_meme);

        TextView topText = (TextView) findViewById(R.id.top_text);
        TextView bottomText = (TextView) findViewById(R.id.bottom_text);
        EditText topEditText = (EditText) findViewById(R.id.top_text_edit);
        EditText bottomEditText = (EditText) findViewById(R.id.bottom_text_edit);
        memeTemplate = (ImageView) findViewById(R.id.meme_image);
        meme = (ViewGroup) findViewById(R.id.meme);

        topEditText.addTextChangedListener(new CopyTextWatcher(topText));
        bottomEditText.addTextChangedListener(new CopyTextWatcher(bottomText));

        Uri uri = parseIntent(getIntent());
        if (uri != null) {
            new DownloadImageAsyncTask().execute(uri);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d(LOG_TAG, "onCreateOptionsMenu");
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.create_meme, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d(LOG_TAG, "onOptionsItemSelected");
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_share) {
            share();
            return true;
        } else if (id == R.id.action_image_capture) {
            photoUri = dispatchImageCaptureIntent();
            return true;
        } else if (id == R.id.action_upload) {
            startAuthenticationAndUploadSequence(); //TODO: starting point.
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
        if (handleActivityResultForAuthentication(requestCode, resultCode, returnedIntent)) {
            return;
        }
        if (requestCode == IMAGE_CAPTURE_REQUEST_CODE) {
            if (resultCode == RESULT_OK && photoUri != null) {
                new DownloadImageAsyncTask().execute(photoUri);
            } else if (resultCode == RESULT_CANCELED) {
                Log.d(LOG_TAG, "User cancelled taking picture.");
            } else {
                Toast.makeText(this, getString(R.string.error_capturing_image), Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * Callback for account selection which starts the upload for the returned account.  May be
     * invoked after recovering from an auth error.
     */
    private boolean handleActivityResultForAuthentication(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_ACCOUNT_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                startAuthenticatedUpload(accountName);
            } else {
                Toast.makeText(this, "Problem picking account", Toast.LENGTH_LONG).show();
            }
            return true;
        } else if (requestCode == AUTHENTICATION_RETRY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                startAuthenticatedUpload(accountName);
            } else {
                Toast.makeText(this, "Problem with authentication retry.", Toast.LENGTH_LONG).show();
            }
            return true;
        }
        return false;
    }

    /** Starts an AsyncTask to perform the upload on a background thread. */
    private void startAuthenticatedUpload(final String accountName) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                doAuthenticatedUpload(accountName);
                return null;
            }
        }.execute();
    }

    /** Performs the upload synchronously. */
    private void doAuthenticatedUpload(final String accountName) {
        Log.i(LOG_TAG, "accountName = " + accountName);
        final String image = save();
        Log.i(LOG_TAG, "Pre_Token = " + token);
        Log.i(LOG_TAG, "image = " + image);
        try {
            token = GoogleAuthUtil.getToken(CreateMemeActivity.this,
                    accountName, "oauth2:" + DriveUploader.AUTHTOKENSCOPE_DRIVE);
            Log.i(LOG_TAG, "token = " + token);
        } catch (UserRecoverableAuthException userAuthEx) {
            // This is an authentication error that we can recover from.
            CreateMemeActivity.this.startActivityForResult(
                    userAuthEx.getIntent(),
                    AUTHENTICATION_RETRY_REQUEST_CODE);
            return;
        } catch (GoogleAuthException e) {
            Log.e(LOG_TAG, "GoogleAuthException", e);
            return;
        } catch (IOException e) {
            Log.e(LOG_TAG, "IOException", e);
            return;
        }

        try {
            final DriveUploader uploader = new DriveUploader(token);
            final String filename = "meme" + Long.toString(System.currentTimeMillis()) + ".jpg";
            final InputStream fileContent =
                    getContentResolver().openInputStream(Uri.parse(image));
            if (/*uploader.uploadToDrive(filename, "image/jpeg", fileContent)*/true) {
                Log.i(LOG_TAG, "Upload successful.");
                //uploader.uploadToDrive(filename, "image/jpeg", fileContent);
                //uploader.getFolders("root");
                InputStream inputStream = uploader.getFolders("");
                WallpaperManager wpm = WallpaperManager.getInstance(this);
                //wpm.setResource(file.toURI());
                //InputStream ins = new URL(filePath).openStream();
                //InputStream ins = new FileInputStream(file);
                wpm.setStream(inputStream);

            } else {
                Log.i(LOG_TAG, "Upload failed.");
                GoogleAuthUtil.invalidateToken(this, token);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "IOException", e);
        }
    }

    private void startAuthenticationAndUploadSequence() {
        if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS) {
            Toast.makeText(this, getString(R.string.gms_connection_failed), Toast.LENGTH_LONG).show();
            return;
        }
        Intent chooseAccountIntent = AccountPicker.newChooseAccountIntent(
                null, // selectedAccount
                null, // allowableAccounts
                new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, // allowableAccountTypes
                false, // alwaysPromptForAccount
                null, // descriptionOverrideText
                DriveUploader.AUTHTOKENSCOPE_DRIVE, // addAccountAuthTokenType
                null, // addAccountRequiredFeatures
                null // addAccountOptions
        );
        startActivityForResult(chooseAccountIntent, PICK_ACCOUNT_REQUEST_CODE);
    }

    private String save() {
        Bitmap bitmap = Bitmap.createBitmap(meme.getWidth(), meme.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        meme.draw(c);
        return MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,
                "meme", "meme");
    }

    private void share() {
        String url = save();

        if (url != null) {
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/jpg");
            share.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
            startActivity(Intent.createChooser(share, getString(R.string.share_tag)));
        } else {
            Toast.makeText(this, "Error sharing the meme!", Toast.LENGTH_LONG).show();
        }
    }

    private Uri parseIntent(Intent intent) {
        if (intent.hasExtra(Intent.EXTRA_STREAM)) {
            return intent.getParcelableExtra(Intent.EXTRA_STREAM);
        }
        if (intent.hasExtra(IMAGE_URL_EXTRA)) {
            return Uri.parse(intent.getStringExtra(IMAGE_URL_EXTRA));
        }
        return Uri.parse(IMAGE_URL);
    }

    private Uri dispatchImageCaptureIntent() {
        Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri resultUri = null;
        if (imageCaptureIntent.resolveActivity(getPackageManager()) != null) {
            resultUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new ContentValues());
            Log.d(LOG_TAG, "Image will be saved to:\n" + resultUri);
            imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri);
            startActivityForResult(imageCaptureIntent, IMAGE_CAPTURE_REQUEST_CODE);
        } else {
            Toast.makeText(
                    this, getString(R.string.error_camera_not_available), Toast.LENGTH_LONG).show();
        }
        return resultUri;
    }

}
